package org.cfx.org.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.cfx.basic.annotation.Permission;
import org.cfx.basic.util.ExcelUtil;
import org.cfx.basic.util.PageList;
import org.cfx.basic.util.RolePermissionCount;
import org.cfx.basic.vo.UserExportVO;
import org.cfx.org.domain.Employee;
import org.cfx.org.domain.Menu;
import org.cfx.org.query.EmployeeQuery;
import org.cfx.org.service.IDepartmentService;
import org.cfx.org.service.IEmployeeService;
import org.cfx.basic.util.AjaxResult;
import org.cfx.org.service.IMenuService;
import org.cfx.org.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author RTX 9090
 *
 *
 * RestFul:请求风格
 *      使用http请求类型替换请求路径里面操作的动词，安全性高
 *      @RequestMapping 可以接收多种请求类型 method = RequestMethod.PUT可以接收单一的请求类型
 *      使用RestFul后不会再使用@RequestMapping
 *          @PutMapping-->接收put请求类型
 *          @DeleteMapping
 */
@RestController
@RequestMapping("/employee")
@Tag(name = "用户管理",description = "用户的CRUD")
@Permission(name = "员工维护")
public class EmployeeController {
    @Resource
    private IDepartmentService departmentService;

    @Resource
    private IEmployeeService employeeService;

    @Autowired
    private IMenuService menuService;

    private static List<UserExportVO> userExportVOS = new ArrayList<>();


//    @RequestMapping(value = "/saveOrUpdate",method = RequestMethod.PUT)
    @PutMapping
    @Operation(summary = "添加或者修改",description = "需要填写用户信息")
    @Permission(name = "添加或者修改")
    public AjaxResult saveOrUpdate(@Parameter(description = "用户信息")
                                       @RequestBody Employee employee) {
        try {
            if ("".equals(employee.getHeadImage())){
                employee.setHeadImage("/images/head/1.png");
            }
            if (employee.getId() == null) {
                employeeService.add(employee);
            } else {
                employeeService.update(employee);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("Error saving employee");
        }
    }

//    @RequestMapping("/delete/{id}")
    @DeleteMapping("/{id}")
    @Operation(summary = "根据id删除用户")
    @Permission(name = "根据id删除用户")
    public AjaxResult delete(@Parameter(description = "填用户id就行了")
                                 @PathVariable("id") Long id) {

        try {
            employeeService.delete(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("Error");
        }
    }

    @DeleteMapping("/deleteList")
    @Operation(summary = "批量删除用户")
    @Permission(name = "批量删除用户")
    public AjaxResult deleteList(@RequestBody ArrayList<Long> ids) {
        try {
            employeeService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false);
        }
    }

//    @RequestMapping("/query/{id}")

    @GetMapping("/{id}")
    @Operation(summary = "根据id查询用户")
    public AjaxResult queryById(@Parameter(description = "填需要查询的用户id就行了")
                                    @PathVariable("id") Long id) {
        return new AjaxResult().setData(employeeService.queryById(id));
    }


    @GetMapping
    @Operation(summary = "查询所有用户")
    public AjaxResult queryAll() {
        List<Employee> employees = employeeService.queryAll();
        return new AjaxResult().setData(employees);
    }

    @PostMapping
    @Operation(summary = "分页+查询所有用户")
    public AjaxResult queryPage(@RequestBody EmployeeQuery employeeQuery) {
        PageList<Employee> employeePageInfo = employeeService.queryAllPage(employeeQuery);
        return new AjaxResult().setData(employeePageInfo);
    }

    @GetMapping("/manager")
    @Operation(summary = "查询所有经理")
    public AjaxResult queryManager() {
        List<Employee> employees = employeeService.queryManager();
        return new AjaxResult().setData(employees);
    }

    // 查询员工的菜单
    @GetMapping("/employee/{employeeId}")
    public AjaxResult getEmployeeMenu(@PathVariable("employeeId")Long employeeId){
        try {
            List<Menu> menus = menuService.getEmployeeMenu(employeeId);
            return AjaxResult.me().setData(menus);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("查询失败!"+e.getMessage());
        }
    }

    @Autowired
    private IUserService userService;

    @PostMapping("/importExcel")
    @CrossOrigin
    public AjaxResult importExcel(@RequestParam("file") MultipartFile file,HttpServletResponse response) {
        try {
            System.out.println(file);
            System.out.println(file.getOriginalFilename());
            String result = userService.importExcel(file);
            return AjaxResult.me().setSuccess(true).setMessage(result);
        } catch (Exception e) {
            return AjaxResult.me().setSuccess(false).setMessage("导入失败");
        }
    }

    @GetMapping("/exportExcel")
    public void export(HttpServletResponse response) {
        //查询要导出的数据
        List<UserExportVO> users = userService.getUserExportList();
        UserExportVO.threadLocal_collectionSize.set( users.size() );
        UserExportVO.threadLocal_insertIndex.set( 1 );
        ExcelUtil.exportExcelX(users, "测试导出表", "sheet1", UserExportVO.class, "测试导出表.xlsx", response);
    }
    @GetMapping("/exportMoreExcel")
    @CrossOrigin
    public void exportMoreExcel(HttpServletResponse response) {
        userExportVOS.forEach(u-> u.setDeptName(u.getDepartment().getName()));
        ExcelUtil.exportExcelX(userExportVOS, "测试导出表", "sheet1", UserExportVO.class, "测试导出表.xlsx", response);
//        userExportVOS.removeAll(userExportVOS);
    }

    @GetMapping("/getCount")
    public AjaxResult getRolePermissionCount() {
        Map<String,List> rolePermissionCount = employeeService.getRolePermissionCount();
        System.out.println(rolePermissionCount);
        return AjaxResult.me().setData(rolePermissionCount);
    }
    @GetMapping("/getRole")
    public AjaxResult getRole() {
        List<RolePermissionCount> role = employeeService.getRole();
        System.out.println(role);
        return AjaxResult.me().setData(role);
    }

//    @PutMapping("/exportMore")
//    public AjaxResult exportMore(@RequestBody ArrayList<UserExportVO> data,HttpServletResponse response) {
//        data.forEach(e-> {
//            UserExportVO roleById = employeeService.getRoleById(e.getId());
//
////            userExportVOS.add(roleById);
//        });
//        ExcelUtil.exportExcelX(userExportVOS, "测试导出表", "sheet1", UserExportVO.class, "测试导出表.xlsx", response);
//        return AjaxResult.me().setSuccess(true).setMessage("导出成功！");
//    }



    @PutMapping("/exportMore")
    public void exportMore11(@RequestBody ArrayList<UserExportVO> data,HttpServletResponse response) {
        List<UserExportVO> userExportVo = new ArrayList<>();
        data.forEach(e-> {
            UserExportVO roleById = employeeService.getRoleById(e.getId());
//            userExportVOS.add(roleById);
            userExportVo.add(roleById);
        });
        UserExportVO.threadLocal_collectionSize.set( userExportVo.size() );
        UserExportVO.threadLocal_insertIndex.set( 1 );
        ExcelUtil.exportExcelX(userExportVo, "测试导出表", "sheet1", UserExportVO.class, "测试导出表.xlsx", response);
//        return AjaxResult.me().setSuccess(true).setMessage("导出成功！");
    }




}
